<!--
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2022-12-26 15:54:32
-->
<template>
    <div class="song-table">
        <el-table :data="songs" stripe style="width: 100%" empty-text="数据加载中~" @row-dblclick="playMusics">
            <el-table-column width="50">
                <!-- 索引或者小喇叭 -->
                <template v-slot="{ row, $index }">
                    <span class="iconfont" :class="music.isplaying ? 'icon-shengyin_shiti' : 'icon-shengyin-guan'"
                        v-if="row.id === music.nowSongDetail.id"></span>
                    <span v-else>{{ $index + 1 }}</span>
                </template>
            </el-table-column>

            <!-- 操作 -->
            <el-table-column label="操作" width="80">
                <template v-slot="{ row, $index }">
                    <div class="operation">
                        <span @click="likesong(row)"    
                            :class="user.likeSongIds.indexOf(row.id) == -1 ? 'iconfont icon-xihuan1' : 'iconfont icon-xihuan'"
                            :title="user.likeSongIds.indexOf(row.id) == -1 ? '喜欢' : '取消喜欢'"></span>
                        <span class="iconfont icon-xiazai" title="下载" @click="downloadMusic(row)"></span>
                    </div>
                </template>
            </el-table-column>

            <!-- 歌曲名 -->
            <el-table-column label="标题" width="400">
                <template v-slot="{ row, $index }">
                    <div class="songname">
                        <span>{{ row.name }}</span>
                        <i class="iconfont icon-vip" v-if="row.fee == 1"></i>
                        <i class="iconfont icon-MV" v-if="row.mv != 0" @click="toMv(row)"></i>
                    </div>
                </template>
            </el-table-column>

            <!-- 歌手 -->
            <el-table-column label="歌手" width="300">
                <template v-slot="{ row, $index }">
                    <div class="singername">
                        <span v-for="(item, index) in row.ar" :key="item.id" @click="toSinger(item)">
                            {{ item.name }}
                        </span>
                    </div>
                </template>
            </el-table-column>

            <!-- 专辑 -->
            <el-table-column label="专辑" width="250">
                <template v-slot="{ row, $index }">
                    <span @click="toAlbum(row)">{{ row.al.name }}</span>
                </template>
            </el-table-column>

            <!-- 歌曲时长 -->
            <el-table-column label="时间">
                <template v-slot="{ row }">
                    <span>{{ instance.proxy.$formatDuration.formatDurations(row.dt) }}</span>
                </template>
            </el-table-column>
        </el-table>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getSongUrl, checkMusic, likeMusic, getEverySongDetail, getUserSongLikeList } from '@/api/playmusic/playmusic.js'
import { useMusicStore } from '@/store/music.js'
import { useUserStore } from '@/store/user.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getItem } from '@/utils/utils.js'
import mitter from '@/utils/mitt.js'
import downloadmusic from '@/utils/downloadMusic.js'

const instance = getCurrentInstance()
let islike = ref(false)
defineProps({
    songs: {
        type: Array,
        default: []
    }
})

const emit = defineEmits(['updateSonglist'])
const route = useRoute()
const router = useRouter()

//声明音乐仓库
let music = useMusicStore()
//声明用户仓库
let user = useUserStore()

//双击歌曲进行播放  并自动传入点击的那一行歌曲的信息
async function playMusics(song) {
    //先判断当前播放的歌曲与点击的歌曲是否一致
    if (music.nowSongDetail.id === song.id) {
        if (music.isplaying === false) {
            //触发，调用处理函数  footer中的播放音乐函数
            mitter.emit('play')
        }
        return;
    }
    //先检查歌曲是否可用
    let res = await checkMusic(song.id)
    if (res.data.success === true) {  //歌曲可用
        //获取歌曲url
        let res1 = await getSongUrl(song.id)

        music.saveSongUrl(res1.data.data[0].url)   //把歌曲播放地址存到仓库中

        //修改播放状态
        music.changePlayState(true)

        //保存当前歌曲详细信息 去重 如果列表不存在相同的歌曲 再添加到历史播放记录
        music.SaveSongDetailAndaddHistoryPlayList(song)

        //把歌曲添加到当前播放列表
        music.addPlayingList(song)

        //保存歌曲总时长等等,并进行格式化时间
        // music.totalTime = instance.proxy.$formatDuration.formatDurations(music.nowSongDetail.dt)
        // music.totalSecond = music.nowSongDetail.dt

    } else {
        instance.appContext.config.globalProperties.$message({
            message: '暂时无法播放(无版权),换首试试',
            type: 'warning',
            showClose: true
        })
    }
}


//喜欢xx音乐
function likesong(song) {
    //先判断登录状态
    if (!user.isLogin) {
        instance.appContext.config.globalProperties.$message({
            type: 'warning',
            message: '登录后才能收藏',
            showClose: true
        })
        return;
    }
    //判断当前点击的歌曲id在不在用户喜欢歌单列表 在决定是喜欢还是不喜欢
    let like = user.likeSongIds.indexOf(song.id) !== -1 ? false : true
    //如果用户是在 用户喜欢的音乐歌单页面点击的，需要确认和重新获取用户喜欢音乐的数据

    //通过路由来判断，userSongList第一个元素即为用户喜欢的音乐歌单
    if (user.userSongList[0].id == route.params.id) {
        //弹出确认框
        ElMessageBox.confirm('确定将选中歌曲从我喜欢的音乐中删除吗？', {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }).then(() => {  //选择确定按钮
            //删除就掉接口
            likeMusicBy(song, like)
            //重新刷新页面，更新歌单
            emit('updateSonglist')
        }).catch(err => {
            ElMessage({
                type: 'warning',
                message: err
            })
        })
    } else
        //如果不是，直接调接口
        likeMusicBy(song, like)
}

//  喜欢/不喜欢某歌曲
async function likeMusicBy(song, like) {
    let res = await likeMusic(song.id, like, getItem('cookie'))
    //请求成功
    if (res.data.code === 200) {
        //重新获取用户喜欢音乐id
        getUserLikSongs()
        if (like === true) {
            ElMessage({
                type: 'success',
                message: '已添加到我喜欢的音乐中',
                showClose: true,
                center: true
            })
            islike.value = true
        } else {
            ElMessage({
                type: 'success',
                message: '取消喜欢成功',
                showClose: true,
                center: true
            })
            islike.value = false
        }
    }
}

//获取用户喜欢音乐id列表
async function getUserLikSongs() {
    let res = await getUserSongLikeList(user.userInfo.userId, getItem('cookie'))
    if (res.data.code === 200) {
        if (Array.isArray(res.data.ids) && res.data.ids.length != 0)
            //调用仓库方法保存
            user.saveLikeSongIds(res.data.ids)
    }
}

//点击下载
function downloadMusic(song) {
    downloadmusic(song)  //使用插件
}


onMounted(() => {
    // 如果没有用户的喜欢列表 就先获取
    if (user.isLogin && user.likeSongIds.length == 0)
        getUserLikSongs()
})


//去歌手详情
function toSinger(singer) {
    router.push('/singerdetail/' + singer.id)
}
//去专辑
function toAlbum(item) {
    router.push('/albumdetail/' + item.al.id)
}
//去mv
function toMv(item) {
    router.push({
        name: 'Videodetail',
        params: { id: item.mv, type: 'mv' }
    })
}

</script>

<style lang="scss" scoped>
.song-table {
    .operation {}
}

.songname {
    display: flex;
    align-items: center;
}

.singername {
    span {
        cursor: pointer;
        margin-right: 5px;

        &:hover {
            color: #fd544e;
        }
    }
}

.icon-xiazai {
    margin-left: 5px;
}

.iconfont {
    cursor: pointer;
}

.icon-vip,
.icon-MV {
    margin-left: 5px;
    color: #fd544e;
}

.icon-xihuan {
    color: #fd544e;
}
</style>